package sskj.regulatory.data.pref

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import com.hikvision.sdk.net.bean.LoginData
import sskj.regulatory.data.network.ApiConstants
import sskj.regulatory.ribble.presentation.utils.extensions.emptyString
import sskj.regulatory.ribble.presentation.utils.extensions.unSafeLazy
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class Preferences @Inject constructor(app: Application) {

    private val SHARED_PREF_NAME = "sskj_shared_pref"
    private val USER_LOGGED_IN = "user_logged_in"
    private val USER_TOKEN = "user_token"
    private val USER_TOKEN_TIME = "user_token_time"

    private val ALONG = "along"
    private val USER_PASSWORD_VIDEO = "user_password_video"
    private val USER_ADDRESS_NET_VIDEO = "user_address_net_video"


    private val sharedPreferences by unSafeLazy {
        app.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE)
    }
    val isUserLoggedIn
        get() = sharedPreferences.getBoolean(USER_LOGGED_IN, false)
    val token: String
        get() = sharedPreferences.getString(USER_TOKEN, "")
    val time: Long
        get() = sharedPreferences.getLong(USER_TOKEN_TIME, 0L)
    val isExpired: Boolean
        get() = Date().time - sharedPreferences.getLong(USER_TOKEN_TIME, 0L) < 60048000
    val isSendVCode: Boolean
        get() = Date().time - sharedPreferences.getLong(ALONG, Date().time) < 59000

    fun saveUserLoggedIn() {
        sharedPreferences.put {
            putBoolean(USER_LOGGED_IN, true)
        }
    }

    fun saveAlong() {
        sharedPreferences.put {
            remove(ALONG)
            putLong(ALONG, Date().time)
        }
    }

    fun saveUserLoggedOut() {
        sharedPreferences.put {
            putBoolean(USER_LOGGED_IN, false)
        }
    }

    infix fun saveUserToken(token: String?) {
        deleteToken()
        sharedPreferences.put {
            putString(USER_TOKEN, token)
            putLong(USER_TOKEN_TIME, Date().time)
        }
    }


    fun deleteToken() {
        sharedPreferences.put {
            remove(USER_TOKEN)
            remove(USER_TOKEN_TIME)
        }
    }
}

private inline fun SharedPreferences.put(body: SharedPreferences.Editor.() -> Unit) {
    val editor = this.edit()
    editor.body()
    editor.apply()
}